<template>
  <div>
    <div v-if="treeDataSourcing.length">
      <a-tree-select
        :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }" labelInValue v-model="treeDataSourcingValue"
        allowClear @change="onchange" :tree-data="treeDataSourcing" treeNodeFilterProp='value' :disabled="isDisabled">
      </a-tree-select>
    </div>
    <div v-else>
      <p v-if='isReadOnlyPage' style="display:flex;">
        <span v-if="revisionEditReadOnlyPage" class="labelColor mr5" style="min-width:70px;">{{ placeholders }}：</span>
        <span class="valueColor">{{ normalizedValue }}</span>
      </p>
      <a-input v-else @click="alertModal" :placeholder="placeholder" :value="normalizedValue" :disabled="isDisabled"/>
      <select-city-modal :visible="selectCityModalVisible" @cancel="selectCityModalVisible = false" :confirmLoading="confirmLoading" :spinning="selectCityModalSpinning" @confirm="confirm" :mode="locationMode ? locationMode : mode" v-model="dataSource"></select-city-modal>
    </div>
  </div>
</template>

<script>
import SelectCityModal from '@/components/SelectCity/SelectCityModal'
import { getCityCitys, getAvailableCityList } from '@/api/config.js'
const treeDataSourcing = []
export default {
  name: 'LocationNew',
  components: { SelectCityModal },
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      // type: Object
    },
    isReadOnlyPage: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: ''
    },
    isDisabled: {
      type: Boolean,
      default: false
    },
    isResume: {
      type: Boolean,
      default: false
    },
    mode: {
      type: String,
      default: 'single'
    },
    locationMode: {
      type: String,
      default: 'single'
    },
    componentInnerLoadData: {
      type: Boolean,
      default: true
    },
    cityData: {},
    revisionEditReadOnlyPage: {
      type: Boolean,
      default: false
    },
    placeholders: {
      type: String,
      default: ''
    },
    values: {},
    cityCanEmpty: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      selectCityModalVisible: false,
      confirmLoading: false,
      selectCityModalSpinning: false,
      dataSource: [],
      getCityCitys,
      treeDataSourcing
    }
  },
  watch: {
    values: {
      handler (newVal) {
        if (newVal) {
          this.treeDataSourcing = resizeTreeSourcing(newVal)
        }
      },
      immediate: true,
      deep: true
    }
  },
  computed: {
    normalizedValue () {
      if (Array.isArray(this.value)) {
        const nameList = this.value.map(item => item.name)
        return nameList.join(',')
      } else {
        if (this.value && this.value.name) {
          return this.value.name
        } else if (this.isResume) {
          return this.value
        }
        return ''
      }
    },
    treeDataSourcingValue () {
      console.log(this.value)
      let obj = {}
      if (this.value) {
        obj = { label: this.value.name, value: this.value.id }
      }
      return obj
    }
  },
  mounted () {
    this.getData()
  },
  methods: {
    getData () {
      if (this.componentInnerLoadData) {
        this.getAvailableCityList()
      } else {
        if (this.cityData && this.cityData.length && this.value && this.value.length) {
          this.dataSource = this.processingData(this.cityData, this.value)
        } else if (this.cityData && this.cityData.length && this.value && this.value.id) {
          this.dataSource = this.processingSingleData(this.cityData, this.value)
        } else {
          this.dataSource = this.cityData
        }
      }
    },
    async getAvailableCityList () {
      this.selectCityModalSpinning = true
      const res = await getAvailableCityList()
      if (res.code === 200) {
        this.selectCityModalSpinning = false
        if (res.data && res.data.length && this.value && this.value.length) {
          this.dataSource = this.processingData(res.data, this.value)
        } else if (res.data && res.data.length && this.value && this.value.id) {
          this.dataSource = this.processingSingleData(res.data, this.value)
        } else {
          this.dataSource = res.data
        }
      }
    },
    processingData (dataSource, data) {
      dataSource.forEach(element => {
        if (element.children && element.children.length) {
          element.children.forEach(province => {
            if (province.children && province.children.length) {
              data.forEach(ele => {
                if (ele.id === province.id) {
                  this.$set(province, 'checkAll', true)
                }
              })
              province.children.forEach(city => {
                data.forEach(ele => {
                  if (ele.id === city.id) {
                    this.$set(city, 'checked', true)
                  }
                })
              })
            } else {
              data.forEach(ele => {
                if (ele.id === province.id) {
                  this.$set(province, 'checkAll', true)
                }
              })
            }
          })
        }
      })
      return dataSource
    },
    processingSingleData (dataSource, data) {
      dataSource.forEach(element => {
        if (element.children && element.children.length) {
          element.children.forEach(province => {
            if (province.children && province.children.length) {
              if (data.id === province.id) {
                this.$set(province, 'checkAll', true)
              }
              province.children.forEach(city => {
                if (data.id === city.id) {
                  this.$set(city, 'checked', true)
                }
              })
            } else {
              if (data.id === province.id) {
                this.$set(province, 'checkAll', true)
              }
            }
          })
        }
      })
      return dataSource
    },
    onchange (val) {
      this.$emit('change', { id: val.value, name: val.label })
    },
    alertModal () {
      this.getData()
      this.selectCityModalVisible = true
    },
    // 确定
    confirm (list) {
      console.log('confirm', list)
      const tempList = list.reduce((init, curr) => {
        init.push(...curr.children)
        return init
      }, [])
      let data = {}
      if (!this.cityCanEmpty) { // 不允许城市清空
        if (!tempList.length) {
          this.$notify.warning('请选择一个省市')
          return
        }
        data = tempList[0].children.length ? tempList[0].children[0] : tempList[0]
      } else { // 允许城市清空
        data = { name: '', id: '' }
      }
      // const data = tempList[0].children.length ? tempList[0].children[0] : tempList[0]
      this.selectCityModalVisible = false
      this.$emit('selectChange', tempList)
      if (this.isResume) {
        this.$emit('change', data.name)
      } else {
        if ((this.mode === 'single' && !this.locationMode) || this.locationMode === 'single') { // 城市输入框单选时，返回对象
          this.$emit('change', data)
        } else { // 多选时，返回数组
          console.log(tempList)
          this.$emit('change', tempList)
        }
      }
      this.$emit('ckeckedKeys', 'city')
      this.$emit('onBlurFn', true)
    }
  }
}
function resizeTreeSourcing (arr, key = 0) {
  if (!Array.isArray(arr)) return
  return arr.map((item, index) => {
    let treekey = `${key}-${index}`
    return { title: item.name, value: item.id, key: item.id, id: item.id, disabled: !item.bselect, children: resizeTreeSourcing(item.children, treekey) }
  })
}
</script>
